import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

import '../log/logger.dart';
import '../widget/lose_network_dialog.dart';
import 'package:path_provider/path_provider.dart';

class HttpHelper{
  static HttpHelper get instance => _getInstance();

  static HttpHelper? _httpHelper;

  static HttpHelper _getInstance() {
    _httpHelper ??= HttpHelper();
    return _httpHelper!;
  }

  late Dio _dio;

  HttpHelper() {

    _dio = Dio();
    _dio.options.connectTimeout = const Duration(seconds: 5);
    _dio.options.receiveTimeout = const Duration(seconds: 30);
    _dio.options.sendTimeout = const Duration(seconds: 30);
    PrettyDioLogger log = PrettyDioLogger(
        requestHeader: true,
        requestBody: true,
        responseBody: true,
        responseHeader: false,
        error: true,
        compact: true,
        maxWidth: 90);
    _dio.interceptors.add(log);

  }

  Future oldPost(String url, {Object? data,Options? options }) async {
    Response response;
    try{
      if (data != null && options != null) {
        response = await _dio.post(url, data: data, options: options);
      } else  if (data != null ) {
        response = await _dio.post(url, data: data);
      }  else {
        response = await _dio.post(url);
      }
    }on DioException catch(e){
      if(e.response != null){
        Logger().write('$url  $data\r\n${e.response!.statusCode}\r\n${e.response!.data}\r\n');
      }else{
        Logger().write('$url  $data\r\n${e.type}\r\n');
      }
      if(e.type == DioExceptionType.receiveTimeout || e.type == DioExceptionType.sendTimeout || e.type == DioExceptionType.connectionTimeout || e.type == DioExceptionType.connectionError){
        // LoseNetworkDialog().openDialog();
        return (500,'请求超时,请检查网络');
      }
      return (e.response!.statusCode,e.response!.data);
    }
    return (response.statusCode,response.data);
  }

  Future post(String url, {Object? data ,Options? options }) async {
    Response response;
    try{
      if (data != null && options != null) {
        response = await _dio.post(url, data: data, options: options);
      } else  if (data != null ) {
        response = await _dio.post(url, data: data);
      }  else {
        response = await _dio.post(url);
      }
    }on DioException catch(e){
      if(e.response != null){
        Logger().write('$url  $data\r\n${e.response!.statusCode}\r\n${e.response!.data}\r\n');
      }else{
        Logger().write('$url  $data\r\n${e.type}\r\n');
      }
      if(e.type == DioExceptionType.receiveTimeout || e.type == DioExceptionType.sendTimeout || e.type == DioExceptionType.connectionTimeout || e.type == DioExceptionType.connectionError){
        LoseNetworkDialog().openDialog();
        return (500,'请求超时,请检查网络');

      }
      return (e.response!.statusCode,e.response!.data);
    }
    return (response.statusCode,response.data);
  }

  Future get(String url, {Object? data,Options? options }) async {
    Response response;
    try{
      if (data != null && options != null) {
        response = await _dio.get(url, data: data, options: options);
      } else  if (data != null ) {
        response = await _dio.get(url, data: data);
      }  else {
        response = await _dio.get(url);
      }
    }on DioException catch(e){
      if(e.response != null){
        Logger().write('$url  $data\r\n${e.response!.statusCode}\r\n${e.response!.data}\r\n');
      }else{
        Logger().write('$url  $data\r\n${e.type}\r\n');
      }
      if(e.type == DioExceptionType.receiveTimeout || e.type == DioExceptionType.sendTimeout || e.type == DioExceptionType.connectionTimeout || e.type == DioExceptionType.connectionError){
        LoseNetworkDialog().openDialog();
        return {'code': 505,};
      }
      return e.response!.data;
    }
    return response.data;
  }

  Future downLoad(String url, {Object? data,Options? options }) async {
    Response response;
    try{
      var td = await getExternalStorageDirectory();
      // String docPath = await Application.fileUtil.getDocPath();//获取document目录
      // String file = docPath + '/' + Application.util.guid() + extension(url);//本地文件名
      print('downloadUrl = ${td!.path}/bookshelf.apk}');
      var downloadUrl = '${td.path}/bookshelf.apk';

      response = await _dio.download(url,downloadUrl,onReceiveProgress: (int count, int total){
        if (total != -1) {
          print('totle = $total, count = $count');
          if(total == count){
            const MethodChannel('toAndroid').invokeMethod('install',{'message':downloadUrl});
            // webSocketHelper.add(updated());
          }
        }
      });

    }on DioException catch(e){
      if(e.response != null){
        Logger().write('$url  $data\r\n${e.response!.statusCode}\r\n${e.response!.data}\r\n');
      }else{
        Logger().write('$url  $data\r\n${e.type}\r\n');
      }
      if(e.type == DioExceptionType.receiveTimeout || e.type == DioExceptionType.sendTimeout || e.type == DioExceptionType.connectionTimeout || e.type == DioExceptionType.connectionError){
        LoseNetworkDialog().openDialog();
        return {'code': 505,};
      }
      return e.response!.data;
    }
    return response.data;
  }

}